package user

import (
	"dy/pkg/code"
	"dy/pkg/jwt"
	"dy/pkg/password"

	"github.com/gin-gonic/gin"
)

func (u *ControllerUser) Register(ctx *gin.Context) {
	type param struct {
		Username string `form:"username" json:"username" binding:"required"`
		Password string `form:"password" json:"password" binding:"required"`
	}
	var request param
	err := ctx.Bind(&request)
	if err != nil {
		code.ErrReturn(ctx, err.Error())
		return
	}
	search := map[string]interface{}{}
	search["name"] = request.Username
	// search["password"] = request.Password
	search["password"], _ = password.EncryptPassword(request.Password)

	userId, err := u.srv.User().Add(ctx, search)
	if err != nil {
		code.ErrReturn(ctx, err.Error())
		return
	}

	token, err := jwt.GetToken(userId)
	if err != nil {
		code.ErrReturn(ctx, err.Error())
		return
	}

	ctx.JSON(200, gin.H{
		"status_code": 0,
		"status_msg":  "success",
		"user_id":     userId,
		"token":       token,
	})
	return
}
